package com.itshare.video.common.config.resolver;

import com.itshare.video.common.annontation.JsonBody;
import com.itshare.video.common.aop.AopPropertyUtils;

import com.itshare.video.common.aop.xss.annontation.CleanXSS;
import com.itshare.video.common.core.constant.enums.ApiInfo;
import com.itshare.video.common.exception.RequestBodyErrorException;
import com.itshare.video.common.util.ValidateUtils;
import com.itshare.video.common.util.XssUtil;
import com.itshare.video.common.web.WebUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;

import org.springframework.stereotype.Component;

import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;

import java.lang.reflect.Field;

/**
 * @Author lyr
 * @create 2020/11/10 11:13
 */
@Lazy
@Component
public class JsonBodyResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(JsonBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
        Class<?> clazz = methodParameter.getParameterType();
        Object jsonBodyDecode = WebUtil.getJson(request,clazz);
        if (jsonBodyDecode==null) {
            throw new RequestBodyErrorException(ApiInfo.BAD_REQUEST);
            // return null;
        }
        //如果 在参数有 cleanXSS 或者 类上打了 xss,自动去检查处理
        //如果要清除XSS
        if (methodParameter.hasParameterAnnotation(CleanXSS.class)  || clazz.isAnnotationPresent(CleanXSS.class)) {
            //存在 安全注解，进行转义
            if (AopPropertyUtils.isJavaApi(clazz)) {
                if (jsonBodyDecode instanceof  String) {
                    CleanXSS mark = methodParameter.getParameterAnnotation(CleanXSS.class);
                    return XssUtil.escapeJSAndHtml(mark,(String)jsonBodyDecode);

                }
            }else {
                 XssUtil.removeXSSWithBean(jsonBodyDecode);
            }
        }
        // BindException bindException = new BindException(jsonBodyDecode, "driver");
        validate.doValidate(methodParameter,jsonBodyDecode);

        return jsonBodyDecode;

        // return WebUtil.getForm(request,clazz);
    }

    //
    @Resource
    private ValidateUtils validate;
    //使用 spring framework的 validator
    // @Resource
    // private Validator validator;



}
